<?php
/**
 * 系統名稱: Platform 系統
 * 檔案說明: 專案管理-修改
 * $Author$
 * $Id$
 *
 */

if (!defined('Common_lib_include')){
    define('Common_lib_include', 1);

	include_once(__Modules_Path."/TransferAPI.lib.php");

	function CheckUsePower($strPmName){
		global $_strSameTip;
		$strPmName = addslashes($strPmName);
		//$strPmName = "/<!--".$strPmName." start-->([^,]*)<!--".$strPmName." end-->/i";
		if(!preg_match("/>".addslashes($strPmName)."::([^,]*)/i", $_SESSION["Admin_Info"] -> ProgramPower, $arrPOWER)){
		//if(!preg_match($strPmName, $_SESSION["Admin_Info"] -> ProgramPower, $arrPOWER)){

			$GLOBALS["errormessage"] = $_strSameTip["sm_NoPower"];
			if($GLOBALS["errormessage"] == "")$GLOBALS["errormessage"] = "Don't have power of this program!!";

			$GLOBALS["errorhidden"] = "\n".$strPmName."\n".$_SESSION["Admin_Info"] -> ProgramPower;
			return false;
		}
		return $arrPOWER;
	}


	//防止變數污染和字元攻擊
	function Protector_Sanitize($arrParam){
		if(is_array($arrParam)){
			if(!empty($arrParam['_SESSION']) ||
			   !empty($arrParam['_COOKIE']) ||
			   !empty($arrParam['_SERVER']) ||
			   !empty($arrParam['_ENV']) ||
			   !empty($arrParam['_FILES']) ||
			   !empty($arrParam['GLOBALS'])
			)exit("Param has limit name!!");

			return array_map('Protector_Sanitize', $arrParam);
		}
		return str_replace("\0", "", $arrParam);
	}


	//防止 SQL Injection
	function Protector_Quotes($arrParam){
		if(is_array($arrParam)){
			return array_map('Protector_Quotes', $arrParam);
		}
		return addslashes($arrParam);
	}


	/**
	 * 取得 Micro Time
	 * @return	float
	 */
	function getMicro_Time(){
		list($usec, $sec) = explode(" ", microtime()); 
		return ((float)$usec + (float)$sec); 
	} 


	/**
	 * 錯誤輸出
	 * @param	strErrTitle 錯誤標題
	 * @param	strViewType 錯誤輸出方式
	 * @param	isExit 是否 Exit(), default 1
	 * @return	false -> 錯誤, true -> 成功, 
	 */
	function ErrMsgOutputHTML($strErrTitle, $strViewType, $isExit = 1){
		$strReplaceLink = "";
		switch($strViewType){
			case "AjaxError":
				header("Content-Type: text/xml");
				$strErrTmpFile = __Admintemplate_Path."/ajax_error.html";
				$GLOBALS["errormessage"] = htmlspecialchars($GLOBALS["errormessage"]);
				$GLOBALS["errorhidden"] = htmlspecialchars($GLOBALS["errorhidden"]);
				break;

			case "AdminNoSession":
				$strErrTmpFile = __Admintemplate_Path."/nosession_error.html";

				$strHOST = $_SERVER["HTTP_HOST"];
				if($_SESSION["RdHttpHost"] != ""){
					$strHOST = $_SESSION["RdHttpHost"];
				}
				$strHOST = str_replace('secure.', '', $strHOST);

				if($strHOST == ""){
					$strReplaceLink = __AdminReplaceLink;
				}elseif(strpos($_SERVER["REQUEST_URI"], "/k_admin") !== false){
					if(strpos(__AdminReplaceLink, "/k_admin") !== false){
						$strReplaceLink = 'http://'.$strHOST."/k_admin";
					}else{
						if($_SESSION["RdHttpHost"] != ""){
							$strReplaceLink = 'http://'.$strHOST."/";
						}else{
							$strReplaceLink = (strpos($strHOST, "admin") === false)?'http://admin.'.$strHOST."/":'http://'.$strHOST."/";
						}
					}
				}elseif(strpos($_SERVER["REQUEST_URI"], "/admin/") !== false){
					if(strpos(__AdminReplaceLink, "/k_admin") !== false){
						$strReplaceLink = 'http://'.$strHOST."/k_admin";
					}else{
						$strReplaceLink = (strpos($strHOST, "admin") === false)?'http://admin.'.$strHOST."/":'http://'.$strHOST."/";
					}
				}else{
					$strReplaceLink = 'http://'.$strHOST."/";
				}

				/*if(strpos(__AdminReplaceLink, $strHOST) === false){
					$strReplaceLink = 'http://admin.'.$strHOST."/";
				}else{
					$strReplaceLink = __AdminReplaceLink;
				}*/
				break;

			case "MemberNoSession":
				$strErrTmpFile = __Admintemplate_Path."/nosession_error.html";

				$strHOST = $_SERVER["HTTP_HOST"];
				if($_SESSION["RdHttpHost"] != ""){
					$strHOST = $_SESSION["RdHttpHost"];
				}
				$strHOST = str_replace('secure.', '', $strHOST);

				if($strHOST != ""){
					if(strpos(__AdminReplaceLink, "www") !== false){
						$strReplaceLink = 'http://'.$strHOST."/";
					}else{
						$strReplaceLink = (strpos($strHOST, "www") === false)?'http://www.'.$strHOST."/":'http://'.$strHOST."/";
					}
				}elseif($strHOST == ""){
					$strReplaceLink = __MemberReplaceLink;
				}else{
					$strReplaceLink = (strpos($strHOST, "www") === false)?'http://www.'.$strHOST."/":'http://'.$strHOST."/";
				}

				/*$strHOST = str_replace('secure.', '', $_SERVER["HTTP_HOST"]);
				if(strpos(__MemberReplaceLink, $strHOST) === false){
					$strReplaceLink = 'http://www.'.$strHOST."/";
				}else{
					$strReplaceLink = __MemberReplaceLink;
				}*/
				break;

			case "RebackError":
				$strErrTmpFile = __Admintemplate_Path."/reback_error.html";

				$strHOST = str_replace('secure.', '', $_SERVER["HTTP_HOST"]);
				if(strpos(__MemberReplaceLink, $strHOST) === false){
					$strReplaceLink = 'http://www.'.$strHOST."/";
				}else{
					$strReplaceLink = __MemberReplaceLink;
				}
				break;

			default:
				$strErrTmpFile = __Admintemplate_Path."/default_error.html";
				break;
		}

		$fp = @file($strErrTmpFile);
		$fp = implode("", $fp);
		$fp = str_replace("big5", "utf-8", $fp);
		$fp = str_replace("{ReplaceLink}", $strReplaceLink, $fp);
		$fp = str_replace("{ErrTitle}", $strErrTitle, $fp);
		$fp = str_replace("{ErrMsgContent}", $GLOBALS["errormessage"]." ", $fp);
		//if($_SESSION["isDebug"])
			$fp = str_replace("{ErrMsgHidden}", $GLOBALS["errorhidden"]." ", $fp);

		print $fp;
		if($isExit)exit();
	}


	/**
	 * 使用者帳號是否符合規定
	 * @param	strAcc 管理者帳號
	 * @return	false -> 錯誤, true -> 成功, 
	 */
	function isCorrectAccount($strAcc){
		return (preg_match("/^([A-z0-9_\@\-]){4,20}$/", $strAcc))?true:false;
	}


	/**
	 * 使用者密碼是否符合規定
	 * @param	strPwd 密碼
	 * @return	false -> 錯誤, true -> 成功, 
	 */
	function isCorrectPassword($strPwd){
		return (preg_match("/^([A-z0-9_\@\-]){6,20}$/", $strPwd))?true:false;
	}


	/**
	 * 取得使用者IP
	 * @return	IP String
	 */
    function getUserRemoteAdd(){
 		$arrIP = explode(",", $_SERVER["HTTP_X_FORWARDED_FOR"]);
		return ($arrIP[0] != "")?$arrIP[0]:$_SERVER["REMOTE_ADDR"];
    }


	/**
	 * 寫入檔案
	 * @param	strPath 檔案路徑
	 * @param	strCon 檔案內容
	 * @param	strMode 寫入模式
	 * @return	false -> 錯誤, true -> 成功, 
	 */
    function writeFile($strPath, $strCon, $strMode = "w"){

		if(!$fp = @fopen($strPath, $strMode)){
			$GLOBALS["errormessage"] = "Open File Error!!";
			$GLOBALS["errorhidden"] = "Path:".$strPath."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		if(!fputs($fp, $strCon)){
			$GLOBALS["errormessage"] = "Input File Error!!";
			$GLOBALS["errorhidden"] = "Path:".$strPath."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		@fclose($fp);
		return true;

    }

	/**
	 * 轉換 HTML Charset
	 * @param	strCon HTML 內容
	 * @return	String -> 成功, 
	 */
	function setHTMLCharset($strCon){
		global $_intLang;
		//$strCon = str_replace("charset=utf-8", "charset="._Charset, $strCon);
		//$strCon = str_replace("{intLang}", _LangCode, $strCon);
		$strCon = str_replace("{intLang}", $_intLang, $strCon);
		$strCon = str_replace("{ctime}", 1, $strCon);
		return $strCon;
	}

	/**
	 * 網站 HTML 輸出
	 * @param	strCon 錯誤標題
	 * @param	isExit 是否 Exit(), default 1
	 * @return	false -> 錯誤, true -> 成功, 
	 */
	function WebOutputHTML($strCon, $isExit = 1){
		global $_Conn, $$_Conn;
		//header("Content-type: text/html");
		//header("Content-Encoding: gzip");
		//print gzencode($fp, 9, FORCE_GZIP);
		@header("Content-Type: text/html; charset=utf-8");
		print $strCon;
		@mysql_close($$_Conn);
		if($isExit)exit();
	}

	/**
	 * 網站 XML 輸出
	 * @param	strCon 錯誤標題
	 * @param	isExit 是否 Exit(), default 1
	 * @return	false -> 錯誤, true -> 成功, 
	 */
	function WebOutputXML($strCon, $isExit = 1){
		global $_Conn, $$_Conn;
		@header("Content-Type: text/xml; charset=utf-8");
		print $strCon;
		@mysql_close($$_Conn);
		if($isExit)exit();
	}

	/**
	 * 取得 Member 是否在線
	 * @return	false -> 錯誤, true -> 成功, 
	 */
	function getMemIsOnLine(){
		if(!isset($_SESSION["Member_Info"]) || !is_object($_SESSION["Member_Info"]))return false;
		if(__isConnectToOtherWeb == 1){
			if(time() - $_SESSION["Member_PFSID_Time"] >= 15){
				if(!getPFAdminIsOnline($_SESSION["Member_PFSID"], $_SESSION["Member_Info"] -> ID, 1))return false;
				$_SESSION["Member_PFSID_Time"] = time();
			}
		}
		return true;
	}

	function getMemIsRightCKey(){
		if($_COOKIE["Member_CKey"] != $_SESSION["Member_Info"] -> CKey && $_SESSION["Member_Info"] -> SuppleID == "")return false;
		return true;
	}

	/**
	 * 取得 Admin 是否在線
	 * @return	false -> 錯誤, true -> 成功, 
	 */
	function getAdminIsOnLine(){
		if(!isset($_SESSION["Admin_Info"]) || !is_object($_SESSION["Admin_Info"]))return false;
		if(__isConnectToOtherWeb == 1){
			if(time() - $_SESSION["Admin_PFSID_Time"] >= 15){
				if(!getPFAdminIsOnline($_SESSION["Admin_PFSID"], $_SESSION["Admin_Info"] -> ID, $_SESSION["Admin_Info"] -> MemberGroup))return false;
				$_SESSION["Admin_PFSID_Time"] = time();
			}
		}
		return true;
	}

	function getAdminIsRightCKey(){
		if($_COOKIE["Admin_CKey"] != $_SESSION["Admin_Info"] -> CKey)return false;
		return true;
	}


	/**
	 * 取得網頁資料
	 * @param	strWebLink 目標網站 Link
	 * @param	strWebHost 目標網站 Host
	 * @param	strPost Post 參數
	 * @return	string
	 */
	//取得網頁資料
	function getWebPageContent($strWebLink, $strWebHost, $strPost){

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $strWebLink);
		curl_setopt($ch, CURLOPT_VERBOSE, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				"Accept:image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-shockwave-flash, */*",
				"User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)",
				"Host:".$strWebHost,
				"Connection:Keep-Alive"));

		if($strPost != ""){	
			curl_setopt ($ch, CURLOPT_POST, 1); 
			curl_setopt ($ch, CURLOPT_POSTFIELDS, $strPost);
		}

		$strCon = curl_exec ($ch);
		curl_close ($ch);
		return $strCon;
	}


	/**
	 * 設置旗標
	 * @param	strFlagName 旗標名稱
	 * @param	intWaitSec 等待旗標消失的時間
	 * @return	string
	 */
	function setFlagToDB($strFlagName, $intWaitSec = 15){
		global $_ConnMaster;

		$strSQL = "insert into `bet_BetControl`(`BetKey`) values( '".$strFlagName."' )";
		while (!PMA_mysql_query($strSQL, $_ConnMaster)) {
			if($i < $intWaitSec){
				$i++;
				sleep(3);
			}else{
				return delFlagToDB($strFlagName);
			}
		}

		return true;
	}

	/**
	 * 移除旗標
	 * @param	strFlagName 旗標名稱
	 * @return	string
	 */
	function delFlagToDB($strFlagName){
		global $_ConnMaster;

		$strSQL = "delete from `bet_BetControl` where `BetKey` = '".$strFlagName."' ";
		@PMA_mysql_query($strSQL, $_ConnMaster);

		return true;
	}
//-------------------------------------------------------//
//End
}
?>